package com.library.infrastructure;

import com.library.domain.Book;
import com.library.domain.BookRepository;
import org.springframework.stereotype.Repository;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Repository
public class InMemoryBookRepository implements BookRepository {
    private final Map<UUID, Book> books = new ConcurrentHashMap<>();

    @Override
    public List<Book> findAll() {
        return new ArrayList<>(books.values());
    }

    @Override
    public Optional<Book> findById(UUID id) {
        return Optional.ofNullable(books.get(id));
    }

    @Override
    public Book save(Book book) {
        if (book.getId() == null) {
            book.setId(UUID.randomUUID());
        }
        books.put(book.getId(), book);
        return book;
    }

    @Override
    public void deleteById(UUID id) {
        books.remove(id);
    }
}